import { createRouter, createWebHashHistory } from "vue-router";
import Cookies from "js-cookie";
import { ElMessage } from "element-plus";

import HomeView from "../views/HomeView";
import LoginView from "../views/LoginView";

const routes = [
  {
    path: "/",
    name: "home",
    component: HomeView,
    redirect: { name: "workstation" },
    children: [
      // 工作台
      {
        path: "/workstation",
        name: "workstation",
        component: () => import("@/components/WorkstationComponent.vue"),
      },
      // 学校管理
      {
        path: "/school",
        name: "school",
        component: () => import("@/components/SchoolManageComponent.vue"),
      },
      // 学校管理员
      {
        path: "/schooladmin",
        name: "schooladmin",
        component: () => import("@/components/SchoolAdminManageComponent.vue"),
      },
      // 教师账号
      {
        path: "/teacher",
        name: "teacher",
        component: () => import("@/components/TeacherManageComponent.vue"),
      },
      // 学生账号
      {
        path: "/student",
        name: "student",
        component: () => import("@/components/StudentManageComponent.vue"),
      },
      // 就业管理
      {
        path: "/employment",
        name: "employment",
        component: () => import("@/components/EmploymentManageComponent.vue"),
      },
      // 个人中心
      {
        path: "/person",
        name: "person",
        component: () => import("@/components/PersonalCenterComponent.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: LoginView,
    meta: {
      noAuth: true, //true为不需要登录也可以进
    },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((r) => r.meta.noAuth)) {
    next();
  } else {
    if (Cookies.get("token")) {
      next();
    } else {
      ElMessage({
        message: "请先登录",
        type: "warning",
      });
      next({
        path: "/login",
      });
    }
  }
});

export default router;
